package chapter04

import chisel3._
import chisel3.util._

class MaskRAM extends Module {
  val io = IO(new Bundle {
    val addr = Input(UInt(10.W))
    val dataIn = Input(UInt(32.W))
    val en = Input(Bool())
    val we = Input(Bool())
    val mask = Input(Vec(4, Bool()))
    val dataOut = Output(UInt(32.W))
  })
  val dataIn_temp = Wire(Vec(4, UInt(8.W)))
  val dataOut_temp = Wire(Vec(4, UInt(8.W)))
  val syncRAM = SyncReadMem(1024, Vec(4, UInt(8.W)))
  dataOut_temp := DontCare
  when(io.en) {
    when(io.we) {
      syncRAM.write(io.addr, dataIn_temp, io.mask)
    }.otherwise {
      dataOut_temp := syncRAM.read(io.addr)
    }
  }
  for (i <- 0 until 4) {
    dataIn_temp(i) := io.dataIn(8 * i + 7, 8 * i)
    io.dataOut := Cat(dataOut_temp(3), dataOut_temp(2), dataOut_temp(1),
      dataOut_temp(0))
  }
}